<?php

if (defined('NO_DIRECT')) {
	if (isset($_POST['status'])) {
		$string = $_POST['status'];
		$string = preg_replace('/\s+/',' ',$string);
		$string = trim($string);

		if (strlen($string) < 1) {
			// ini gagal bos
			echo 'kosong bos';
		} elseif (strlen($string) > 140) {
			// ini gagal bos
			echo 'lebih dari 140 bos';
		} else {
			$string = str_replace('{','&o;',$string);
			$string = str_replace('}','&c;',$string);
			
			// laksanakan parsing
			$mentions = array();
			$topics = array();
			$chunks = explode(' ',$string);
			foreach ($chunks as $key => $chunk) {
				if ($chunk[0] == '@' && strlen($chunk) > 1) {
					$user = db_result('SELECT user_id FROM users WHERE username = "'.urlencode(substr($chunk,1)).'"');
					if ($user !== false) {
						if (!in_array($user['user_id'],$mentions)) {
							$chunks[$key] = '{@|'.substr($chunk,1).'|'.$user['user_id'].'}';
							$mentions[] = $user['user_id'];
						}
					}
				} elseif ($chunk[0] == '#' && strlen($chunk) > 1) {
					if (!in_array(substr($chunk,1),$topics)) {
						$chunks[$key] = '{#|'.substr($chunk,1).'}';
						$topics[] = strtolower(substr($chunk,1));
					}
				} elseif (preg_match('/[\w\d\.]+\.[\w\d]{1,3}/',$chunk)) {
					if (strlen($chunk) > 7) {
						if (substr($chunk,0,7) == 'http://') {
							$chunk = substr($chunk,7);
						}
					}
					if (strlen($chunk) > 4) {
						if (substr($chunk,0,4) == 'www.') {
							$chunk = substr($chunk,4);
						}
					}
					$chunks[$key] = '{l|'.$chunk.'}';
				}
			}
			$string = implode(' ',$chunks);
			
			// masukin ke db tweetnya, mentions, topics, links. diescape dulu yaa
			$datetime = date('Y-m-d H:i:s');
			$reply_to = isset($_POST['reply_to']) ? intval($_POST['reply_to']) : 0;
			if ($reply_to > 0) {
				if (!in_array($reply_to.'',$mentions)) {
					$mentions[] = $reply_to.'';
				}
			}
			$id_status = db_insert('INSERT INTO status (stat_date,stat_user,stat_txt,reply_stat,restat_from) VALUES ("'.$datetime.'",'.$session['user']['user_id'].',"'.amankan($string).'",'.$reply_to.',0)');
			foreach ($mentions as $mention) {
				db_insert('INSERT INTO mentions (mention_stat,mention_who) VALUES ('.$id_status.','.$mention.')');
			}
			foreach ($topics as $topic) {
				db_insert('INSERT INTO topics (topic_stat,topic_tag) VALUES ('.$id_status.',"'.amankan($topic).'")');
			}
			
			// berhasil oye oye
			echo 'berhasil oye oye';
		}
	}
}
